import wepy from 'wepy'
import { isArray, difference } from 'lodash'
import { api, storageKey } from '../config'
import Tips from './tips'

/**
 * 获取用户信息
 *
 * @returns {Promise.<*>}
 */
const getUserInfo = async () => {
  await checkScope(['scope.userInfo'])
  const loginData = await wepy.login()
  const userinfo = await wepy.getUserInfo({
    withCredentials: true,
    lang: 'zh_CN'
  })
  userinfo.code = loginData.code
  return userinfo
}

/**
 * 验证用户授权
 *
 * @param scopes 权限列表
 * @param cancel 能否取消
 * @returns {Promise.<void>}
 */
const checkScope = async (scopes, cancel = false) => {
  const scopesList = [
    'scope.userInfo',
    'scope.userLocation',
    'scope.address',
    'scope.invoiceTitle',
    'scope.werun',
    'scope.record',
    'scope.writePhotosAlbum'
  ]
  const scopesListText = {
    'scope.userInfo': '用户信息',
    'scope.userLocation': '地理位置',
    'scope.address': '通讯地址',
    'scope.invoiceTitle': '发票抬头',
    'scope.werun': '运动步数',
    'scope.record': '录音功能',
    'scope.writePhotosAlbum': '保存相册'
  }
  let unAuthScopes = []
  let needAuthScopes = []
  let unAuthScopesText = []
  let scopesContent = ''
  const scopesContentDelimiter = ' * '
  // 不是数组，不在官方 scopes 列表
  if (!isArray(scopes) || !difference(scopes, scopesList).length === 0) {
    return
  }
  // 获取授权信息
  let setting = await wepy.getSetting()
  scopes.forEach(scope => {
    // 从未授权过
    if (setting.authSetting[scope] === undefined) {
      needAuthScopes.push(scope)
    }
    // 用户不允许授权
    if (!setting.authSetting[scope]) {
      unAuthScopes.push(scope)
      unAuthScopesText.push(scopesListText[scope])
    }
  })

  // 从未授权过的，预授权
  if (needAuthScopes.length > 0) {
    for (let needAuthScope of needAuthScopes) {
      await wepy.authorize({
        scope: needAuthScope
      }).catch((
      ) => {})
    }
  }

  // 存在未授权
  if (unAuthScopes.length > 0) {
    // 拼接内容并且弹窗
    scopesContent = scopesContentDelimiter + unAuthScopesText.join(`\n${scopesContentDelimiter}`)
    let status = await wepy.showModal({
      title: '微信授权',
      content: `申请获得以下权限: \n${scopesContent}`,
      showCancel: cancel, // 是否显示拒绝按钮
      confirmText: '允许',
      cancelText: '拒绝'
    })

    // 拒绝授权
    if (status.cancel) {
      return
    }
    // 打开设置，让用户授权
    let userSetting = await wepy.openSetting()
    unAuthScopes.forEach(scope => {
      // 仍然没授权 递归要求授权 递归出口 1、授权 2、拒绝
      if (!userSetting.authSetting[scope]) {
        checkScope(scopes, cancel)
      }
    })
  }
}
/**
 * 登陆获取 token
 *
 * @returns {Promise.<void>}
 */
const login = async () => {
  let userInfoRaw = {}
  let tokenInfo = {}

  // 显示提示窗
  Tips.loading('登陆中', false)
  try {
    userInfoRaw = await getUserInfo()
    tokenInfo = await wepy.request({
      url: api.auth.loginByMiniProgram.url,
      method: api.auth.loginByMiniProgram.method,
      data: userInfoRaw
    })
    await wepy.setStorage({
      key: storageKey.accessToken,
      data: tokenInfo.data.access_token
    })
    // 关闭提示窗
    Tips.loaded()
    return tokenInfo
  } catch (e) {
    wepy.showModal({
      title: '提示',
      content: `登陆失败，请关闭重新进入。${e.message}`
    })
  }
}
export default {
  getUserInfo,
  checkScope,
  login
}
